package com.yljk.yljkproject.aliyunface;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.aliyun.aliyunface.ToygerConst;
import com.aliyun.aliyunface.ToygerPresenter;
import com.aliyun.aliyunface.config.AndroidClientConfig;
import com.aliyun.aliyunface.config.OSSConfig;
import com.aliyun.aliyunface.config.Protocol;
import com.aliyun.aliyunface.config.SDKAction;
import com.aliyun.aliyunface.log.RecordLevel;
import com.aliyun.aliyunface.log.RecordService;
import com.aliyun.aliyunface.network.NetworkEnv;
import com.aliyun.aliyunface.network.NetworkPresenter;
import com.aliyun.aliyunface.network.ZimInitCallback;
import com.aliyun.aliyunface.ui.OcrGuideFrontActivity;
import com.aliyun.aliyunface.ui.ToygerLandActivity;
import com.aliyun.aliyunface.ui.ToygerPortActivity;
import com.aliyun.aliyunface.ui.widget.iOSLoadingView;
import com.aliyun.aliyunface.utils.EnvCheck;
import com.yljk.yljkproject.R;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Create By shicheng
 *
 * 阿里云人脸识别Loading识别
 *
 */
public class MyFaceLoadingActivity extends AppCompatActivity {
    private static final int TOYGER_PERMISSION_REQUEST_CODE = 1024;
    private static String[] toygerPermissions = new String[]{"android.permission.CAMERA"};
    private Handler uiHandler = new Handler(new Handler.Callback() {
        public boolean handleMessage(Message message) {
            int msgType = message.what;
            if (903 == msgType) {
                String errCode = (String)message.obj;
                MyFaceLoadingActivity.this.onErrorCode(errCode);
            } else if (909 == msgType) {
                MyFaceLoadingActivity.this.onInitDeviceSuccess();
            }

            return false;
        }
    });

    public MyFaceLoadingActivity() {
    }

    private boolean isOcrEnabled() {
        AndroidClientConfig sdkCfg = ToygerPresenter.getInstance().getAndroidClientConfig();
        if (null == sdkCfg) {
            return false;
        } else {
            ArrayList<SDKAction> actionList = sdkCfg.getSdkActionList();
            if (null != actionList && actionList.size() > 0) {
                Iterator var3 = actionList.iterator();

                SDKAction action;
                do {
                    if (!var3.hasNext()) {
                        return false;
                    }

                    action = (SDKAction)var3.next();
                } while(!"ocr".equalsIgnoreCase(action.actionName));

                return true;
            } else {
                return false;
            }
        }
    }

    private void onInitDeviceSuccess() {
        Intent bizIntent = null;
        if (this.isOcrEnabled()) {
            bizIntent = new Intent(this, OcrGuideFrontActivity.class);
        } else {
            Intent loadingIntent = this.getIntent();
            if (null != loadingIntent) {
                String screenOrientation = loadingIntent.getStringExtra("ext_params_key_screen_orientation");
                if (null != screenOrientation && !TextUtils.isEmpty(screenOrientation) && screenOrientation.equalsIgnoreCase("ext_params_val_screen_land")) {
                    bizIntent = new Intent(this, ToygerLandActivity.class);
                }
            }

            if (null == bizIntent) {
                bizIntent = new Intent(this, MyToygerPortActivity.class);
            }
        }

        this.startActivity(bizIntent);
        this.finish();
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_face_loading);
        this.handlePermissionsAndInit();
    }
    @SuppressLint("WrongConstant")
    private void showiOSLoading(boolean show) {
        iOSLoadingView iOSLoadingView = (iOSLoadingView)this.findViewById(R.id.iOSLoadingView);
        if (null != iOSLoadingView) {
            if (show) {
                iOSLoadingView.setVisibility(0);
            } else {
                iOSLoadingView.setVisibility(4);
            }
        }

    }

    @SuppressLint("WrongConstant")
    private List<String> genUnGrantedToygerPermissions() {
        List<String> requestPerms = new ArrayList();
        if (Build.VERSION.SDK_INT >= 23) {
            String[] var2 = toygerPermissions;
            int var3 = var2.length;

            for(int var4 = 0; var4 < var3; ++var4) {
                String permission = var2[var4];
                if (0 != this.checkSelfPermission(permission)) {
                    requestPerms.add(permission);
                }
            }
        }

        return requestPerms;
    }

    private void handlePermissionsAndInit() {
        if (Build.VERSION.SDK_INT >= 23) {
            List<String> requestPerms = this.genUnGrantedToygerPermissions();
            if (requestPerms.size() > 0) {
                RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "androidPermissionFail", new String[]{"status", "permissions not granted, left size=" + requestPerms.size(), "android_sdk", String.valueOf(Build.VERSION.SDK_INT)});
                this.requestPermissions((String[])requestPerms.toArray(new String[0]), 1024);
                return;
            }
        }

        RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "androidPermssionOK", new String[]{"status", "permissions already granted, enter sdk", "android_sdk", String.valueOf(Build.VERSION.SDK_INT)});
        this.init();
    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        List<String> perms = this.genUnGrantedToygerPermissions();
        if (requestCode == 1024 && perms.size() <= 0) {
            RecordService.getInstance().recordEvent(RecordLevel.LOG_ERROR, "androidPermissionOK", new String[]{"status", "permissions granted, after user comfirm, enter sdk", "android_sdk", String.valueOf(Build.VERSION.SDK_INT)});
            this.init();
        } else {
            RecordService.getInstance().recordEvent(RecordLevel.LOG_ERROR, "androidPermissionFail", new String[]{"status", "permissions not granted after user confirm, exit sdk", "android_sdk", String.valueOf(Build.VERSION.SDK_INT)});
            this.sendErrorCode(ToygerConst.ZcodeConstants.ZCODE_NO_CAMERA_PERMISSION);
        }

    }

    private void sendErrorCode(String errCode) {
        Message msg = Message.obtain();
        msg.what = 903;
        msg.obj = errCode;
        this.uiHandler.sendMessage(msg);
    }

    private void onErrorCode(String errCode) {
        if (TextUtils.isEmpty(errCode)) {
            errCode = ToygerConst.ZcodeConstants.ZCODE_SYSTEM_EXC;
        }

        this.sendResponseAndFinish(errCode);
    }

    private void sendResponseAndFinish(String errCode) {
        RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "LoadingActivityFinish", new String[]{"status", "exit"});
        this.finish();
        ToygerPresenter.getInstance().sendResAndExit(errCode);
    }

    private void init() {
        EnvCheck.EnvErrorType errCode = EnvCheck.check();
        if (EnvCheck.EnvErrorType.ENV_SUCCESS != errCode) {
            if (EnvCheck.EnvErrorType.ENV_ERROR_LOW_OS == errCode) {
                this.sendErrorCode(ToygerConst.ZcodeConstants.ZCODE_OS_VERSION_LOW);
            } else if (EnvCheck.EnvErrorType.ENV_ERROR_NO_FRONT_CAMERA == errCode) {
                this.sendErrorCode(ToygerConst.ZcodeConstants.ZCODE_NO_FRANT_CAMERA);
            }

            RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "enviromentCheckFail", new String[]{"result", "false"});
        } else {
            RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "enviromentCheckOK", new String[]{"result", "success"});
            String zimId = ToygerPresenter.getInstance().getZimId();
            String metaInfo = "";
            Intent intent = this.getIntent();
            if (null != intent && intent.hasExtra("toyger_meta_info")) {
                metaInfo = intent.getStringExtra("toyger_meta_info");
            }

            this.showiOSLoading(true);
            RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "startNetInit", new String[]{"zimId", zimId, "meta", metaInfo});
            NetworkEnv networkEnv = ToygerPresenter.getInstance().getNetworkEnv();
            if (null == networkEnv) {
                this.sendErrorCode(ToygerConst.ZcodeConstants.ZCODE_SYSTEM_EXC);
            } else {
                NetworkPresenter.zimInit(networkEnv, zimId, metaInfo, new ZimInitCallback() {
                    public void onSuccess(String protocol, OSSConfig ossConfig) {
                        RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "netInitResOK", new String[]{"netSuccess", "true", "protocol", protocol, "ossConfig", ossConfig.toString()});

                        try {
                            Protocol protoObject = (Protocol) JSON.parseObject(protocol, Protocol.class);
                            protoObject.parse(protoObject.content);
                            if (!protoObject.isValid()) {
                                RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "netInitResParseError", new String[]{"parseResult", "false", "protocol", protocol, "oss", ossConfig.toString()});
                                MyFaceLoadingActivity.this.sendErrorCode(ToygerConst.ZcodeConstants.ZCODE_NET_INIT_ERROR);
                                return;
                            }

                            ToygerPresenter.getInstance().setAndroidClientProtocol(protoObject);
                            ToygerPresenter.getInstance().setOssConfig(ossConfig);
                            RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "netInitResParseOK", new String[]{"parseResult", "true", "protocol", protocol, "oss", ossConfig.toString()});
                            MyFaceLoadingActivity.this.uiHandler.sendEmptyMessage(909);
                        } catch (Exception var4) {
                            RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "netInitResException", new String[]{"parseSuccess", "false", "protocol", protocol, "oss", ossConfig.toString()});
                            MyFaceLoadingActivity.this.sendErrorCode(ToygerConst.ZcodeConstants.ZCODE_NET_INIT_ERROR);
                        }

                    }

                    public void onServerError(String code, String message) {
                        RecordService.getInstance().recordEvent(RecordLevel.LOG_ERROR, "netInitResServerError", new String[]{"status", code, "msg", message});
                        MyFaceLoadingActivity.this.sendErrorCode(code);
                    }

                    public void onError(String code, String message) {
                        RecordService.getInstance().recordEvent(RecordLevel.LOG_ERROR, "netInitResNetError", new String[]{"netSuccess", "false", "code", String.valueOf(code), "msg", message});
                        MyFaceLoadingActivity.this.sendErrorCode(code);
                    }
                });
            }
        }
    }
}